package com.adcc.ags.gms.user.controller;

import com.adcc.ags.gms.core.util.Constant;
import com.adcc.ags.gms.core.util.LogFactory;
import com.adcc.ags.gms.core.vo.JSONResultVO;
import com.adcc.ags.gms.core.vo.ResultState;
import com.adcc.ags.gms.core.vo.ResultVO;
import com.adcc.ags.gms.user.entity.Route;
import com.adcc.ags.gms.user.service.RouteService;
import com.adcc.ags.gms.user.vo.GWUserTreeVO;
import com.adcc.ags.gms.user.vo.GWUserVO;
import com.adcc.ags.gms.user.vo.RouteVO;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 用户路由控制层
 */
@Controller
@RequestMapping(value = "/route", produces = MediaType.APPLICATION_JSON_VALUE)
public class RouteController {

    @Autowired
    private RouteService routeService;

    @Autowired
    private LogFactory log;

    /**
     * 初始化网关用户树
     * @return
     */
    @RequestMapping(value = "/initGWUserTree", method = RequestMethod.GET)
    public @ResponseBody JSONResultVO initGWUserTree() {
        JSONResultVO resultVO = new JSONResultVO();
        try {
            Optional<GWUserTreeVO> optional = routeService.initGWUserTree();
            if (optional.isPresent()) {
                resultVO.setData(optional.get().toJson());
            }else{
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(RouteController.class, "initGWUserTree() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    /**
     * 初始化网关用户列表
     * @return
     */
    @RequestMapping(value = "/initGWUserList", method = RequestMethod.GET)
    public @ResponseBody ResultVO initGWUserList(long userId) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<List<GWUserVO>> optional = routeService.initGWUserList(userId);
            if (optional.isPresent()) {
                resultVO.getData().put("gwUserVO",optional.get());
            }else{
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(RouteController.class, "initGWUserList() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    /**
     * 根据用户ID查询路由
     * @param id
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/{id}/findRouteByUserId", method = RequestMethod.GET)
    public @ResponseBody ResultVO findRouteByUserId(@PathVariable("id")long id, int currentPage, int pageSize) {
        ResultVO resultVO = new ResultVO();
        List<RouteVO> voList = Lists.newArrayListWithExpectedSize(100);
        try {
            Optional<PageInfo<Route>> option1 = routeService.findRouteByUserId(id, currentPage, pageSize);
            if (option1.isPresent()) {
                resultVO.setPageInfo(option1.get());
                for (Route route : option1.get().getList()) {
                    RouteVO vo = new RouteVO(route);

                    // 获取目标网关用户名称
                    if (vo.getDestinationId() != null && vo.getDestinationId().size() > 0) {
                        String[] idArray = vo.getDestinationId().toArray(new String[vo.getDestinationId().size()]);
                        List<String> list = routeService.findUserNameById(idArray);
                        if (list != null && list.size() > 0) {
                            for(String destinationName : list){
                                vo.getDestinationName().add(destinationName);
                            }
                        }
                    }
                    voList.add(vo);
                }
                resultVO.getData().put("routeVO", voList);
            } else {
                resultVO.setState(ResultState.FAILURE);
                resultVO.setCode(-1);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
            return resultVO;
        } catch (Exception ex) {
            log.error(RouteController.class, "findRouteByUserId() error", ex);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setCode(-1);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
            return resultVO;
        }
    }

    /**
     * 根据用户名和类型查询用户路由
     * @param userId
     * @param name
     * @param type
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/findRouteByNameAndType", method = RequestMethod.GET)
    public @ResponseBody ResultVO findRouteByNameAndType(String name,int type,long userId,int currentPage, int pageSize) {
        ResultVO resultVO = new ResultVO();
        try {
            List<RouteVO> voList = Lists.newArrayListWithExpectedSize(100);
            Optional<PageInfo<Route>> option1 = routeService.findRouteByNameAndType(name,type,userId,currentPage,pageSize);
            if (option1.isPresent()) {
                resultVO.setPageInfo(option1.get());
                for (Route route : option1.get().getList()) {
                    RouteVO vo = new RouteVO(route);

                    // 获取目标网关用户名称
                    if (vo.getDestinationId() != null && vo.getDestinationId().size() > 0) {
                        String[] idArray = vo.getDestinationId().toArray(new String[vo.getDestinationId().size()]);
                        List<String> list = routeService.findUserNameById(idArray);
                        if (list != null && list.size() > 0) {
                            for(String destinationName : list){
                                vo.getDestinationName().add(destinationName);
                            }
                        }
                    }
                    voList.add(vo);
                }
                resultVO.getData().put("routeVO", voList);
            } else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
            return resultVO;
        } catch (Exception ex) {
            log.error(RouteController.class, "getAllRouteConfigsByConditions() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
            return resultVO;
        }
    }

    /**
     * 创建用户路由
     * @param routeConfig
     * @param session
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody ResultVO createRoute(RouteVO routeConfig, HttpSession session) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = routeService.createRoute(routeConfig);
            if (!optional.isPresent()) {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(RouteController.class, "createRoute() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    /**
     * 修改路由
     * @param id
     * @param vo
     * @param session
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public @ResponseBody ResultVO updateRoute(@PathVariable("id") long id, @RequestBody RouteVO vo, HttpSession session) {
        ResultVO resultVO = new ResultVO();
        try {
            Optional<Boolean> optional = routeService.updateRoute(vo);
            if (!optional.isPresent()) {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception e) {
            log.error(RouteController.class, "update routeConfig fail", e);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    /**
     * 删除用户路由
     * @param ids
     * @param session
     * @return
     */
    @RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
    public  @ResponseBody  ResultVO deleteRoute(@PathVariable("ids") String[] ids, HttpSession session) {
        ResultVO resultVO = new ResultVO();
        try {
            //批量删除
            Optional<Boolean> optional = routeService.deleteSelectedRoute(ids);
            if(!optional.isPresent()){
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(RouteController.class, "deleteRoute() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
        }
        return resultVO;
    }

    /**
     * 通过用户ID 获取queue名称 （用来显示路由目的地址）
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/getRouteByUserIds", method = RequestMethod.GET)
    public @ResponseBody ResultVO findRouteByUserIds(String[] ids) {
        ResultVO resultVO = new ResultVO();
        if (ids != null) {
            try {
                Optional<List<String>> list = null;
                if (list.isPresent() && list.get().size() > 0) {
                    resultVO.getData().put("reciList", list.get());
                }
            } catch (Exception e) {
                log.error(RouteController.class, "getRouteByUserIds  fail", e);
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_SERVER_ERROR);
            }
        } else {
            resultVO.getData().put("reciList", null);
        }
        return resultVO;
    }

    /**
     * 验证用户名是否存在
     *
     * @param routeName
     * @return
     */
    @RequestMapping(value = "/checkName", method = RequestMethod.GET)
    public @ResponseBody ResultVO checkName(String routeName) {
        ResultVO resultVO = new ResultVO();
        String strName = Strings.nullToEmpty(routeName);
        try {
            Optional<Boolean> optional = routeService.isExistRouteName(strName);
            if (optional.isPresent()) {
                if (optional.get()) {
                    resultVO.setCode(0);
                    resultVO.setState(ResultState.FAILURE);
                    resultVO.setReason("路由名称已存在");
                }
            } else {
                resultVO.setCode(-1);
                resultVO.setState(ResultState.FAILURE);
                resultVO.setReason(Constant.GMS_DB_ERROR);
            }
        } catch (Exception ex) {
            log.error(RouteController.class, "findAllRouteConfigsById() error", ex);
            resultVO.setCode(-1);
            resultVO.setState(ResultState.FAILURE);
            resultVO.setReason(Constant.GMS_SERVER_ERROR);
            return resultVO;
        }
        return resultVO;
    }

}
